import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'

import { InputIds, OutputIds } from './constants'
import Tab from '../components/tab/tab'
import css from './runtime.less'
function EditRender({ env, data, inputs, outputs, slots }: any) {
  const [activeKey, setActiveKey] = useState(data.statusList?.[0]?.id || undefined)
  let active = activeKey
  if (data.statusList && data.statusList.length > 0) {
    if (!data.statusList.some((item: any) => item.id == active)) {
      active = data.statusList[0].id
    }
  }
  return (
    <div className={css['box']}>
      <Tab
        actived={activeKey}
        onChange={setActiveKey}
        items={data.statusList.map((status: any) => {
          const id = status.id
          let title = status.title
          if (![undefined, null].includes(status.value)) {
            title += `(${status.value})`
          }
          return {
            label: title,
            value: id
          }
        })}
      />
      {slots?.[active]?.render?.()}
    </div>
  )
}
function RuntimeRender({ env, data, inputs, outputs, slots }: any) {
  const [value, setValue] = useState<string | undefined>(data.value)
  const id = data.statusList?.find?.((item) => item.value == value)?.id
  inputs[InputIds.SetValue]((val, relOutput) => {
    setValue(val)
    relOutput[OutputIds.SetValueDone](val)
  })

  inputs[InputIds.GetValue]((val, relOutput) => {
    relOutput[OutputIds.ReturnValue](value)
  })
  return (
    <>
      {Object.entries<any>(slots).map(([slotId, slot]) => (
        <div className={`${css['item']} ${slotId == id ? css['show'] : ''}`} key={slotId}>
          {slot.render()}
        </div>
      ))}
    </>
  )
}

export default function (props: any) {
  return props.env.edit ? <EditRender {...props} /> : <RuntimeRender {...props} />
}
